package com.bupt.ilink.controller;

import com.bupt.ilink.entity.Studyspace.tree.JsonEntity;
import com.bupt.ilink.entity.Studyspace.tree.JsonTagEntity;
import com.bupt.ilink.entity.Studyspace.tree.TagEntity;
import com.bupt.ilink.entity.Studyspace.tree.UploadJsonRequest;
import com.bupt.ilink.entity.User;
import com.bupt.ilink.request.Study.UpdateJsonStatusRequest;
import com.bupt.ilink.entity.Studyspace.StudyTeacherCoursesFavorite;
import com.bupt.ilink.entity.Studyspace.tree.*;
import com.bupt.ilink.entity.User;
import com.bupt.ilink.service.MinioService;
import com.bupt.ilink.service.OssService;
import com.bupt.ilink.service.StudyTreeFavoriteService;
import com.bupt.ilink.service.StudyTreeJsonService;
import com.bupt.ilink.utils.R;
import com.bupt.ilink.utils.SnowflakeIdGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.bind.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/StudyTree/json")
public class StudyTreeJsonController {

    @Autowired
    private StudyTreeJsonService studyTreeJsonService;

    @Autowired
    private StudyTreeFavoriteService studyTreeFavoriteService;

    @Autowired
    private OssService ossService;

    /**
     * @author dzy
     * @return 最常使用的8个标签(List<TagEntity>形式)
     */
    @GetMapping("/getCommonStudyTreeTags")
    public R getCommonStudyTreeTags(){
        try {
            return R.ok(studyTreeJsonService.getCommonTags());
        } catch(Exception e){
            return R.failure("内部服务器错误：" + e);
        }
    }

    @GetMapping("/tags")
    public R getAllTags() {
        return R.ok(studyTreeJsonService.getAllTags());
    }

    // 关键词，标签，分页查找
    @GetMapping
    public R getJsonsByTagsAndPagination(
            @RequestParam List<String> tags,
            @RequestParam String  keyword,
            @RequestParam int page,
            @RequestParam int size) {
        return R.ok(studyTreeJsonService.getJsonsByTagsAndPagination(tags,keyword, page, size));
    }

    @GetMapping("/detail")
    public R getJsonById(@RequestParam Long id) {
        return R.ok(studyTreeJsonService.getJsonById(id));
    }



    @GetMapping("/getUrl")
    public R geturl(String filename){
        return R.ok(null,ossService.getStudyTreeResourceUrl ("dataset-square","json_resource/" + filename));
    }


    /*
    编写人：张博
    用途：技能树用户个人收藏
     */
    @PostMapping("/add_favorite_tree")
    public  R addFavoriteTree(@AuthenticationPrincipal UserDetails userDetails,
                                @RequestParam String treeId){
        try{
            User user = (User) userDetails;
            String userId = user.getUserId();
            if(studyTreeFavoriteService.insertFavoriteTree(userId, Long.valueOf(treeId))){
                return R.ok("用户已经该技能树新增至收藏夹");
            }
            return R.failure("收藏技能树失败");
        } catch (Exception e){
            return R.failure(e);
        }
    }

    /*
    编写人：张博
    用途：返回指定用户的收藏列表
     */
    // 获取指定用户的收藏列表
    @GetMapping("/list_favorite")
    public R getFavoriteList(@AuthenticationPrincipal UserDetails userDetails) {
        try{
            User user = (User) userDetails;
            String userId = user.getUserId();

            List<StudyTreeFavorite> favoriteList = studyTreeFavoriteService.getFavoriteListByUserId(userId);
            if(favoriteList != null){
                return R.ok(user.getUsername()+"用户的列表",favoriteList);
            }
            return R.failure("用户未收藏技能树");
        }catch (Exception e){
            return R.failure("获取用户的收藏列表错误"+e.getMessage());
        }
    }

    @PostMapping("/upload")
    public R uploadJson(@RequestBody UploadJsonRequest request) {
        ObjectMapper objectMapper = new ObjectMapper();

        // Step 1: Create a new JsonEntity and set its fields
        JsonEntity jsonEntity = new JsonEntity();
        jsonEntity.setName(request.getName());
        jsonEntity.setDescription(request.getIntroduction());
        jsonEntity.setImageUrl(request.getProjectImage());

        try {
            String jsonContent = objectMapper.writeValueAsString(request.getContent());
            jsonEntity.setJsonContent(jsonContent);
        } catch (Exception e) {
            return R.failure("Invalid JSON content format");
        }

        // Step 2: Save the JsonEntity
        studyTreeJsonService.saveJsonEntity(jsonEntity);

        // Step 3: Process tags and save them in the database
        List<Long> tagIds = new ArrayList<>();
        if (request.getTaps() != null) {
            for (String tagName : request.getTaps()) {
                TagEntity tagEntity = studyTreeJsonService.getOrCreateTag(tagName);
                tagIds.add(tagEntity.getTagId());
            }

            // Step 4: Save JsonTagEntity for each tag
            for (Long tagId : tagIds) {
                JsonTagEntity jsonTagEntity = new JsonTagEntity();
                jsonTagEntity.setJsonId(jsonEntity.getId());
                jsonTagEntity.setTagId(tagId);
                studyTreeJsonService.saveJsonTagEntity(jsonTagEntity);
            }
        } else {
            return R.failure("Tags (Taps) cannot be null or empty");
        }

        return R.ok("JSON uploaded successfully");
    }


    @PostMapping("/update_status")
    public R updateJsonStatus(@RequestBody UpdateJsonStatusRequest updateJsonStatusRequest){

        studyTreeJsonService.updateJsonStatus(updateJsonStatusRequest);
        return R.ok("技能树状态更新成功");
    }

    @GetMapping("/insert_status")
    public R testInsert(){
        studyTreeJsonService.storeJsonCopiesForUser("ca96b2942b14380264");
        return R.ok("创建成功");
    }


}
